from datetime import datetime
from typing import Optional
from pydantic import BaseModel, EmailStr
from bson import ObjectId

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("Invalid objectid")
        return ObjectId(v)

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="string")

class UserBase(BaseModel):
    username: str
    email: EmailStr
    avatar: Optional[str] = None

class UserCreate(UserBase):
    password: str

class UserUpdate(BaseModel):
    username: Optional[str] = None
    email: Optional[EmailStr] = None
    avatar: Optional[str] = None

class UserInDBBase(UserBase):
    id: PyObjectId
    created_at: datetime
    updated_at: datetime
    last_login: Optional[datetime] = None
    is_active: bool = True
    wallet_balance: float = 0.0

    class Config:
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

class User(UserInDBBase):
    pass

class UserInDB(UserInDBBase):
    password_hash: str